<?php


namespace app\controller\admin;


use app\BaseController;
use app\common\UserLevel;
use app\models\coupon\CouponModel;
use app\models\user\UserLevelModel;
use app\models\user\UserModel;
use app\services\user\DetailIntegralService;
use app\services\user\DetailMoneyService;
use app\services\user\UserCouponService;
use think\facade\Db;

class MemberController extends BaseAdminController
{
    function setSearch()
    {
        return [
            'like' => ['nick', 'mobile']
        ];
    }

    function setSort()
    {
        return [
            'inviter_name' => 'inviter',
            'level_name' => 'level',
        ];
    }

    /**
     * 用户列表
     * @return \think\response\Json
     */
    public function getList()
    {
        try {
            $where = [];
            $next = $this->request->param('next', '', 'trim');
            if ($next) {
                $userId = UserModel::where('mobile', $next)->value('id');
                $where[] = ['inviter', '=', $userId];
            }
            $team = $this->request->param('team', '', 'trim');
            if ($team) {
                $userId = UserModel::where('mobile', $next)->value('id');
                $where[] = ['referrer', 'like', '%' . $userId . '%'];
            }
            $searchWhere = $this->searchWhere;
            $where = array_merge($where, $searchWhere);
            $orderBy = $this->orderBy;
            $sort = $this->sort;
            $list = UserModel::where($where)
                ->order($orderBy, $sort)
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $v['inviter_name'] = UserModel::where('id', $v['inviter'])->value('nick');
                $v['level_name'] = UserLevelModel::where('id', $v['level_id'])->value('name');
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getPaymentList()
    {
        try {
            $where = [];
            $params = $this->request->param();
            if (isset($params['user_name'])) {
                $where[] = ['b.nick', 'like', '%' . trim($params['user_name']) . '%'];
            }
            if (isset($params['mobile'])) {
                $where[] = ['b.mobile', 'like', '%' . trim($params['mobile']) . '%'];
            }
            $list = Db::name('user_payment')
                ->alias('a')
                ->field('a.*,b.nick,b.mobile')
                ->leftJoin('user b', 'b.id = a.user_id')
                ->where($where)
                ->order('a.id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getUserLevelArr()
    {
        try {
            $list = UserLevelModel::where('status', 0)->select();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function moveUser($id, $mobile)
    {
        try {

            $newUserInfo = Db::name('user')->where('mobile', $mobile)->find();
            if (!$newUserInfo) {
                throw new \Exception("上级不存在");
            }
            $userInfo = Db::name('user')->where('id', $id)->find();
            if (!$userInfo) {
                throw new \Exception("用户不存在");
            }
            if ($userInfo['inviter'] == $newUserInfo['id']) {
                throw new \Exception("新旧关系一致，无需调整");
            }
            // $nextUser = Db::name('user')->where('inviter', $id)->where('status',0)->find();
            // if ($nextUser) {
            //     throw new \Exception("当前用户还有下级，无法更换上级");
            // }
            Db::name('user')->where('id', $id)->update([
                'inviter' => $newUserInfo['id'],
                'referrer' => $newUserInfo['referrer'] . $id . '-',
                'update_time' => time()
            ]);
            $childList = Db::name('user')
                ->where('id', '<>', $id)
                ->where('referrer', 'like', '%' . $id . '%')
                ->select();
            foreach ($childList as $value) {
                $relation = getStringAfter($value['referrer'], (string)$id);
                $relation = $newUserInfo['referrer'] . $id . $relation;
                Db::name('user')->where('id', $value['id'])->update([
                    'referrer' => $relation,
                ]);
            }
            return $this->success();
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    public function delUser()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id');
            $userInfo = Db::name('user')->where('id', $id)->find();
            if (!$userInfo) {
                throw new \Exception("用户不存在");
            }
            Db::name('user')->where('id', $id)->delete();
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    public function editUser()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id');
            $userInfo = UserModel::find($id);
            if (!$userInfo) {
                throw new \Exception("用户不存在");
            }
            // 修改上级
            $newMobile = $this->request->param('new_mobile', '', 'trim');
            if ($newMobile) {
                $this->moveUser($id, $newMobile);
            }
            // 修改手机号
            $mobile = $this->request->param('mobile', '', 'trim');
            if ($mobile) {
                if (!isPhoneNumber($mobile)) {
                    throw new \Exception("手机号错误");
                }
                $newUserInfo = UserModel::where('mobile', $mobile)->find();
                if ($newUserInfo && $newUserInfo['id'] != $id) {
                    throw new \Exception("手机号已存在，不能使用改手机号");
                }
                Db::name('user')->where('id', $id)->update([
                    'mobile' => $mobile,
                    'update_time' => time()
                ]);
            }
            // 修改昵称
            $userName = $this->request->param('nick', '', 'trim');
            if ($userName) {
                Db::name('user')->where('id', $id)->update([
                    'nick' => $userName,
                    'update_time' => time()
                ]);
            }

            // 添加或减少余额
            $addScore = $this->request->param('add_score');
            $lessScore = $this->request->param('less_score');
            if ($addScore > 0) {
                $type = DetailMoneyService::ADMIN_ADD;
                DetailMoneyService::create($id, $type, $addScore, 0, '', DetailMoneyService::getTypeText($type));
            }
            if ($lessScore > 0) {
                if ($userInfo['money'] < $lessScore) {
                    throw new \Exception('余额不足，扣除失败');
                }
                $type = DetailMoneyService::ADMIN_REDUCE;
                DetailMoneyService::create($id, $type, $lessScore, 0, '', DetailMoneyService::getTypeText($type));
            }
            // 添加或减少积分
            $addIntegral = $this->request->param('add_integral');
            $lessIntegral = $this->request->param('less_integral');
            if ($addIntegral > 0) {
                $type = DetailIntegralService::ADMIN_ADD;
                DetailIntegralService::create($id, $type, $addIntegral);
            }
            if ($lessIntegral > 0) {
                if ($userInfo['integral'] < $lessIntegral) {
                    throw new \Exception('积分不足，扣除失败');
                }
                $type = DetailIntegralService::ADMIN_REDUCE;
                DetailIntegralService::create($id, $type, $lessIntegral);
            }
            // 修改用户等级
//            $level = $this->request->param('level_id');
//            $nick = $this->request->param('nick', '', 'trim');
//            $userInfo->nick = $nick;
//            $userInfo->level_id = $level;
            $userInfo->save();
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取发放优惠券列表
     * @return \think\response\Json
     */
    public function getCouponList()
    {
        try {
            $list = CouponModel::where('status', 0)
                ->where('start_time', '<', time())
                ->where('end_time', '>', time())
                ->field('id,coupon_name,amount')
                ->select();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 发放优惠券
     * @return \think\response\Json
     */
    public function sendCoupon()
    {
        try {
            $type = $this->request->param('send_type');
            $uids = $this->request->param('user_ids');
            $couponId = $this->request->param('coupon_id', 0);
            if ($type == 0 && count($uids) == 0) {
                throw new \Exception('请选择发放的用户');
            }
            if (!$couponId) {
                throw new \Exception('请选择发放的优惠券');
            }
            if ($type == 1) {
                $uids = UserModel::where('id', '>', 0)->column('id');
            }
            UserCouponService::sendCoupon($uids, $couponId);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }


}